package arithmetic.cglibProxy;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * @author jiangfeng 2019/8/6 14:59
 *
 * 测试CgLib的动态代理写法
 */
public class CGLib {
    public static void main(String[] args) {
        //normalInvoke();

        proxyInvoke();
    }

    private static void proxyInvoke() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                if (args != null && args.length > 0 && args[0] instanceof User) {
                    User user = (User) args[0];
                    if (user.userName == null || user.userName.trim().length() <= 1) {
                        throw new RuntimeException("用户名不能小于1");
                    }
                }
                Object result = proxy.invokeSuper(obj, args);
                //Object result = method.invoke(args);
                System.out.println("代理成功!" + result);
                return result;
            }
        });

        // 写法错误 死循环
        /*enhancer.setCallback(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                System.out.println("111111111");
                Object invoke = method.invoke(proxy, args);

                return invoke;
            }
        });*/

        UserService userServiceProxy = (UserService) enhancer.create();
        userServiceProxy.addUser(new User("111", 10));
    }

    private static void normalInvoke() {
        User user = new User("1",10);
        new UserService().addUser(user);
    }


}
